package com.bluemsun.naturallanguageprocessing.service.impl;

import com.bluemsun.naturallanguageprocessing.dao.GoodMapper;
import com.bluemsun.naturallanguageprocessing.exception.good.UserDoGoodException;
import com.bluemsun.naturallanguageprocessing.exception.good.UserUnDoGoodException;
import com.bluemsun.naturallanguageprocessing.service.IGoodService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static java.sql.Types.NULL;

@Service
public class GoodServiceImpl implements IGoodService {

    @Resource
    private GoodMapper goodMapper;

    private static final int DO_GOOD_SUCCESS = 1;
    private static final int UNDO_GOOD_SUCCESS = 1;
    @Override
    public int userDoGood(int userId, int questionId) {
        Integer num = goodMapper.userDoGood(userId,questionId);
        if(num == 1){
            return DO_GOOD_SUCCESS;
        }else if(num == 0){
            throw new UserDoGoodException("用户已经点赞");
        }else {
            throw new UserDoGoodException("用户点赞异常");
        }
    }

    @Override
    @Transactional
    public int userUnDoGood(int userId, int questionId) {
        //先检查是否点赞
        Integer num = goodMapper.queryUserGoods(userId,questionId);
        //用户已经点赞
        if(num == 1){
            //取消点赞
            int check = goodMapper.userUndoGood(userId, questionId);
            if(check == 1)
                return UNDO_GOOD_SUCCESS;
            else {//取消点赞异常
                throw new UserUnDoGoodException("取消点赞异常,数据库返回数据非法");
            }
        }else if (num == 0){//用户没有点赞
            throw new UserUnDoGoodException("用户并未点赞");
        }else {//取消点赞异常
            throw new UserUnDoGoodException("点赞异常,数据库返回数据非法");
        }
    }
}
